`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    17:50:06 03/27/2014 
// Design Name: 
// Module Name:    bullet 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module enemy_bullet(clk,rand,new_bullet,position_x, position_y,position_valid,enemy_pos_x,enemy_pos_y);
input clk,new_bullet;//if an new bullet needs to be generated, the module will detect the posedge of the generation_require signal.
input [15:0] rand;
input [9:0] enemy_pos_x,enemy_pos_y;
output reg [9:0] position_x, position_y;
output reg position_valid;//if the bullet is out of range, the signal will goes to 0.

reg [20:0] freq_count_x, freq_count_y;
reg x_clk;
reg y_clk;
reg x_clk_previous,new_bullet_previous;
reg y_clk_previous;

initial freq_count_x <= 0;
initial freq_count_y <= 0;
initial position_valid <= 1;
initial position_x <= 10'd560;
initial x_clk <= 0;
initial y_clk <= 0;

always @ (posedge clk)
begin
	x_clk_previous <= x_clk;
	if (freq_count_x == 1680000)//speed on the x_axis
	begin
		x_clk <= ~x_clk;
		freq_count_x <= 0;
	end
	else
		freq_count_x <= freq_count_x + 1;
	
	y_clk_previous <= y_clk;
	if (freq_count_y == 1680000)//speed on the y_axis
	begin
		y_clk <= ~y_clk;
		freq_count_y <= 0;
	end
	else
		freq_count_y <= freq_count_y + 1;
	
	new_bullet_previous <= new_bullet;
	if (new_bullet_previous == 0 & new_bullet == 1)
		position_x <= 10'd560;
	else
		if (x_clk_previous == 0 & x_clk == 1)
			position_x <= position_x - 3;
	
	if (new_bullet_previous == 0 & new_bullet == 1)			
		position_y <= 100 + rand[8:1];	
		
	if (position_x < 5| position_y > 480)
		position_valid <= 0;
	else
		position_valid <= 1;
		
end
endmodule